<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/18
 * Time: 15:03
 */

namespace common\business\empphoto;


use common\business\upload\UploadHelper;
use common\helpers\StringUtil;
use common\models\EmployeePhoto;
use common\models\kingdee\HrPersonPhoto;
use common\models\kingdee\OrgAdmin;
use common\models\kingdee\Person;
use common\result\ActionResult;
use yii\db\Exception;
use yii\db\Query;

class EmployeePhotoService
{
    /**
     * @var string
     */
    protected $_department_number;
    public function setDepartmentNumber($department_number){
        $this->_department_number = $department_number;
    }

    /**
     * @param callback|null $writeBackHandler
     * @return ActionResult
     */
    public function sync($writeBackHandler = null){
        $totalResult = new ActionResult();

        $db = Person::getDb();

        if (!StringUtil::isNullOrWhiteSpace($this->_department_number)){
            $org = OrgAdmin::findOne([
                'FNUMBER' => $this->_department_number
            ]);

            $orgIdParams = [
                'fid' => $org->FID
            ];
            $cmd = $db->createCommand('SELECT t.fid FROM T_ORG_ADMIN t START WITH t.fid = :fid CONNECT BY t.fparentid = PRIOR fid', $orgIdParams);
//        $cmd->bindParam('fid', $orgId);
            try {
                $orgIdArr = $cmd->queryColumn();
            } catch (Exception $e) {
                return null;
            }
        }

        $query = (new Query())->from('T_BD_PERSON TBP')
            ->leftJoin('T_HR_PERSONPHOTO THPPO', 'THPPO.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_PERSONPOSITION THPP', 'THPP.FPERSONID = TBP.FID')
            ->select([
                'employee_name' => 'TBP.FNAME_L2',
                'employee_number' => 'TBP.FNUMBER',
                'image_content_type' => 'THPPO.FIMAGECONTENTTYPE',
                'image_data' => 'THPPO.FIMAGEDATA',
                'image_width' => 'THPPO.FSOURCEIMAGEWIDTH',
                'image_height' => 'THPPO.FSOURCEIMAGEHEIGHT',
//                'image_source_data' => 'THPPO.FIMAGEDATASOURCE',
            ]);
        if (!StringUtil::isNullOrWhiteSpace($this->_department_number)){
            $query->andFilterWhere([
                'in' , 'THPP.FPERSONDEP', $orgIdArr
            ]);
        }
        $query->orderBy([
            'TBP.FID' => SORT_ASC,
        ]);

        $totalCount = $query->count('*', $db);

        $offset = 0;
        $pageSize = 1000;
        $count = $pageSize;

        while ($count >= $pageSize) {
            $all = $query->offset($offset)->limit($pageSize)->all($db);
            $count = count($all);
            $offset += $pageSize;
            foreach ($all as $item){
                $newObj = new EmployeePhoto();

                if ($item['image_data']){
                    $person = Person::findOne(['FNUMBER' => $item['employee_number']]);
                    $pf = HrPersonPhoto::findOne(['FPERSONID' => $person->FID]);

                    $imageData = stream_get_contents($pf->FIMAGEDATA);
                    $item['image_data'] = $imageData;

                    if ($item['image_content_type']){
                        $fileExtArr = explode('/', $item['image_content_type']);
                        $uploadResult = UploadHelper::uploadEmployeePhotoFileToBackend($item['employee_number'], $item['employee_name'], $fileExtArr[1], $imageData);
                    }
                    $item['image_url'] = sprintf('/employee/get-photo/?number=%s', $item['employee_number']);
                }
//                if ($item['image_source_data']){
//                    $person = Person::findOne(['FNUMBER' => $item['employee_number']]);
//                    $pf = HrPersonPhoto::findOne(['FPERSONID' => $person->FID]);
//
//                    $imageSourceData = stream_get_contents($pf->FIMAGEDATASOURCE);
//                    $item['image_source_data'] = $imageSourceData;
//
////                    if ($item['image_content_type']){
////                        $fileExtArr = explode('/', $item['image_content_type']);
////                        $uploadResult = UploadHelper::uploadEmployeePhotoFile($item['employee_number'], $item['employee_name'], $fileExtArr[1], $imageData);
////                    }
//                }

                $newObj->setAttributes($item);

                $objInDb = EmployeePhoto::findOne([
                    'employee_number' => $newObj->employee_number,
                ]);

                $api = new EmployeePhotoApiHandler();
                if (!$objInDb){
                    $totalResult->addSubResult($api->createEmployeePhoto($newObj));
                }
                else {
                    $totalResult->addSubResult($api->updateEmployeePhoto($newObj, $objInDb));
                }
                if ($writeBackHandler){
                    $paramArr = [
                        'totalCount' => $totalCount,
                        'finishCount' => $totalResult->total_count,
                        'message' => $totalResult->message,
                    ];
                    call_user_func_array($writeBackHandler, $paramArr);
                }
            }
        }
        return $totalResult;
    }
}